package com.zjsru.plan2023.oneday;

/**
 * @Author: cookLee
 * @Date: 2023-10-06
 * 买卖股票的最佳时机含手续费
 */
public class MaxProfit2 {

    /**
     * 主
     * \
     * 输入：prices = [1, 3, 2, 8, 4, 9], fee = 2
     * 输出：8
     * 解释：能够达到的最大利润:
     * 在此处买入 prices[0] = 1
     * 在此处卖出 prices[3] = 8
     * 在此处买入 prices[4] = 4
     * 在此处卖出 prices[5] = 9
     * 总利润: ((8 - 1) - 2) + ((9 - 4) - 2) = 8
     * \
     * 输入：prices = [1,3,7,5,10,3], fee = 3
     * 输出：6
     * \
     * @param args args
     */
    public static void main(String[] args) {
        MaxProfit2 maxProfit2 = new MaxProfit2();
        int[] prices = new int[]{1, 3, 2, 8, 4, 9};
        int fee = 2;
        System.out.println(maxProfit2.maxProfit(prices, fee));
    }

    public int maxProfit(int[] prices, int fee) {
        int len = prices.length;
        int[][] store = new int[len][2];
        //初始化最初的股票数
        store[0][0] = 0;
        store[0][1] = -prices[0];
        for (int i = 1; i < len; i++) {
            //store[i][0]表示交易完后手里没有股票的最大利润
            store[i][0] = Math.max(store[i - 1][0], store[i - 1][1] + prices[i] - fee);
            //store[i][1]表示交易完后手里持有一支股票的最大利润
            store[i][1] = Math.max(store[i - 1][1], store[i - 1][0] - prices[i]);
        }
        return store[len - 1][0];
    }

}
